<!-- mapping文件上传 -->
<template>
  <el-input v-model="mappingId" placeholder="请输入mapping.txt文件对应的MappingId(MappingId是用户自定义的mapping.txt的唯一标识，请在上传前填好)"
    clearable>
    <template #prepend>MappingId</template>
  </el-input>

  <div style="margin: 20px 0"></div>
  <el-upload ref="upload" v-loading="loading" class="upload-view" :action="getUploadUrl()" name="mapping_file" drag
    :limit="1" auto-upload :before-upload="beforeMappingUpload" :on-success="uploadSuccess" :on-error="uploadError"
    :on-progress="uploadProgress">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <template #tip>
      <div class="el-upload__tip">只能上传 text 文件，且不超过 80MB</div>
    </template>
  </el-upload>
</template>
<script>
import { defineComponent } from "vue";
import * as RetraceApi from "./common/api";
export default defineComponent({
  name: "MappingUplaod",
  data() {
    return {
      mappingId: "",
      loading: false,
    };
  },
  methods: {
    getUploadUrl() {
      return RetraceApi.getMappingUploadUrl(this.mappingId);
    },
    uploadSuccess(response) {
      console.log(response); //{"code": 1,"message": "success","serial": 1624180925292,"data": ""}
      if (response.code == 1) {
        this.$message.success("上传成功!");
      } else {
        this.$message.error("上传失败,请重新尝试!");
      }

      this.loading = false;
      this.$refs.upload.clearFiles();
    },

    uploadError(err) {
      this.loading = false;
      console.log(err);
      this.$message.error("上传失败,请重新尝试!");
      this.$refs.upload.clearFiles();
    },
    uploadProgress(event) {
      this.loading = true;
      console.log(event);
    },
    beforeMappingUpload(file) {
      if (this.mappingId.trim() == "") {
        this.$message.error("mappingId不能为空");
        return false;
      }
      const isText = file.type === "text/plain";
      const isLt2M = file.size / 1024 / 1024 < 80;

      if (!isText) {
        this.$message.error("只能上传文本文件!");
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 80MB!");
      }
      return isText && isLt2M;
    },
  },
  mounted() { },
});
</script>

<style scoped>
</style>